import { observable, action, runInAction, flow, computed } from 'mobx'

const state = observable({
  count: 0
})

// 计算属性在函数式定义的方式中，
// 调用的时候需要get()
const double = computed(() => {
  return state.count * 2
})

const setState = action((state) => {
  state.count++
})

const initState = action(() => {
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(100)
    }, 2000)
  })
  .then((value) => {
    // 在mobx里实现异步
    runInAction(() => {
      state.count = value
    })
  })
})

const initState2 = flow(function* () {
  let result = yield new Promise((resolve) => {
    setTimeout(() => {
      resolve(100)
    }, 2000)
  })
  state.count = result
})

export default {
  state,
  double,
  setState,
  initState,
  initState2
}